package com.jt.service;

import com.jt.pojo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/11/5
 */
@PropertySource("classpath:/properties/image.properties")
@Service
public class FileServiceImpl implements FileService{

    @Value("${image.fileLocalDir}")
    private String rootDirPath ;

    @Value("${image.urlPath}")
    private String urlPath;

    private static Set<String> imageTypeSet = new HashSet<>();
    static {
        imageTypeSet.add(".jpg");
        imageTypeSet.add(".png");
        imageTypeSet.add(".gif");
    }


    /**
     * 完善的校验的过程
     * 1. 校验是否为图片
     * 2. 校验是否为恶意程序
     * 3. 防止文件数量太多,分目录存储.
     * 4. 防止文件重名
     * 5. 实现文件上传.
     * @param uploadFile
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile uploadFile){
        String filename = uploadFile.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf(".")).toLowerCase() ;
        if (!imageTypeSet.contains(fileType)){
            return ImageVO.fail();
        }
        try {
            BufferedImage image = ImageIO.read(uploadFile.getInputStream());
            int height = image.getHeight();
            int width= image.getWidth();
            if (height==0||width==0){
                return ImageVO.fail();
            }
            String dir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            File dirFile = new File(String.format("%s/%s", rootDirPath,dir));
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            filename = UUID.randomUUID().toString().replace("-", "");
            String url = String.format("%s%s%s", dir,filename,fileType);
            uploadFile.transferTo(new File(String.format("%s%s", rootDirPath,url)));

            return ImageVO.success(String.format("%s%s",urlPath,url), width, height);
        }catch (Exception e){
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
